/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.unipar.cursoweb.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

/**
 * @author Thiago Marques
 */
@FacesConverter(value = "converterCnpjCpf")
public class ConverterCnpjCpf implements Converter {

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (value == null) {
            return "";
        }
        value = value.replace(".", "").replace("/", "").replace("-", "");
        return value;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (value != null || !"".equals(value)) {
            String valor = ((String) value).trim();
            String doc = "";
            if (valor.length() == 14) {
                doc += valor.substring(0, 2).concat(".");
                doc += valor.substring(2, 5).concat(".");
                doc += valor.substring(5, 8).concat("/");
                doc += valor.substring(8, 12).concat("-");
                doc += valor.substring(12, 14);
                return doc;
            } else if (valor.length() == 11) {
                doc += valor.substring(0, 3).concat(".");
                doc += valor.substring(3, 6).concat(".");
                doc += valor.substring(6, 9).concat("-");
                doc += valor.substring(9, 11);
                return doc;
            }
        }
        return "";

    }
}
